<template>
  <div class="app-container">
    <div class="filter-container">
      <slot name="showFilter"/>
      <el-button v-waves v-if="data.table.showExport" :loading="downloadLoading" style="margin-left: 10px;float: right" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">{{ $t('table.export') }}</el-button>
      <el-button v-if="data.table.showAdd" class="filter-item" style="margin-left: 10px;float: right" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      ref="generateTreeTable"
      :key="tableKey"
      :data="formatData"
      :border="data.table.border"
      :stripe="data.table.stripe"
      :row-style="showRow"
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="selsChange">
      <!--<el-table-column v-if="data.table.showRemove" type="selection" width="55"/>-->
      <!--<el-table-column label="序号" align="center" width="50" type="index"/>-->
      <!--      <el-table-column fixed label="序号" align="center">
        <template slot-scope="scope">
          <span v-for="space in scope.row._level" :key="space" class="ms-tree-space"/>
          <span v-if="iconShow(0,scope.row)" class="tree-ctrl" @click="toggleExpanded(scope.$index)">
            <i v-if="!scope.row._expanded" class="el-icon-plus"/>
            <i v-else class="el-icon-minus"/>
          </span>
          {{ scope.$index }}
        </template>
      </el-table-column>-->

      <el-table-column v-if="data.table.showIndexCol" fixed label="序号" width="60" align="center">
        <template slot-scope="scope"><span>{{ scope.$index+(listQuery.page - 1) * listQuery.limit + 1 }} </span></template>
      </el-table-column>

      <template v-for="(item, index) in data.list">
        <template v-if="item.type == 'grid'">
          <template v-for="col in item.columns" >
            <template v-for="(citem, cindex) in col.list" >
              <el-table-column :prop="citem.model" :label="citem.name" :min-width="citem.options.width" :key="citem.key" :formatter="citem.formatter" :remote="remote" align="center">
                <template slot-scope="scope">
                  <!-- eslint-disable-next-line vue/no-confusing-v-for-v-if -->
                  <span v-for="space in scope.row._level" v-if="cindex === 0" :key="space" class="ms-tree-space"/>
                  <span v-if="iconShow(cindex,scope.row)" class="tree-ctrl" @click="toggleExpanded(scope.$index)">
                    <i v-if="!scope.row._expanded" class="el-icon-plus"/>
                    <i v-else class="el-icon-minus"/>
                  </span>
                  <template v-if="citem.formatter">
                    <span> {{ citem.formatter(scope.row,scope.column,scope.row[scope.column.property],scope.$index) }} </span>
                  </template>
                  <template v-else-if="(citem.type == 'date' || citem.type == 'time') && citem.options.timestamp ">
                    <span> {{ scope.row[citem.model]| formatDate(citem.options.format) }}</span>
                  </template>
                  <template v-else-if="citem.type == 'selecttmep' ">
                    <span> {{ scope.row[citem.model]| getCodeValue(citem, remote) }}</span>
                  </template>
                  <template v-else>
                    <span> {{ scope.row[citem.model] }}</span>
                  </template>
                </template>
              </el-table-column>
            </template>
          </template>
        </template>
        <template v-else>
          <el-table-column :prop="item.model" :label="item.name" :min-width="item.options.width" :key="item.key" :formatter="item.formatter" :remote="remote" align="center">
            <template slot-scope="scope">
              <!-- eslint-disable-next-line vue/no-confusing-v-for-v-if -->
              <span v-for="space in scope.row._level" v-if="index === 0" :key="space" class="ms-tree-space"/>
              <span v-if="iconShow(index,scope.row)" class="tree-ctrl" @click="toggleExpanded(scope.$index)">
                <i v-if="!scope.row._expanded" class="el-icon-plus"/>
                <i v-else class="el-icon-minus"/>
              </span>
              <template v-if="item.formatter">
                <span> {{ item.formatter(scope.row,scope.column,scope.row[scope.column.property],scope.$index) }} </span>
              </template>
              <template v-else-if="(item.type == 'date' || item.type == 'time')&& item.options.timestamp">
                <span> {{ scope.row[item.model]| formatDate(item.options.format) }}</span>
              </template>
              <template v-else-if="item.type == 'selecttmep' ">
                <span> {{ scope.row[item.model]| getCodeValue(item, remote) }}</span>
              </template>
              <template v-else>
                <span> {{ scope.row[item.model] }}</span>
              </template>
            </template>
          </el-table-column>
        </template>
      </template>
      <el-table-column v-if="data.table.showRemove|data.table.showEdit" label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="data.table.showEdit" type="success" icon="el-icon-edit" circle @click="handleUpdate(scope.row)"/>
          <el-button v-if="data.table.showRemove" type="info" icon="el-icon-delete" circle @click="handleDelete(scope.row)"/>
        </template>
      </el-table-column>
      <slot/>
    </el-table>

    <div class="pagination-container">
      <!--<el-button v-if="data.table.showRemove" :disabled="sels.length===0" type="danger" @click="batchRemove">删除</el-button>-->
      <el-pagination v-show="total>0" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <slot :data="temp" form="dataForm" name="table_dialog">
        <generate-form ref="dataForm" :data="data" :remote="remote" :value="temp"/>
      </slot>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import GenerateForm from '@/components/CreateForm/GenerateForm'
import '@/components/CreateForm/styles/FormCreate.css'
import { fetchList, createArticle, updateArticle } from '@/api/table'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import { formatDate } from 'element-ui/packages/date-picker/src/util'
import treeToArray from './eval'
export default {
  name: 'GenerateTreeTable',
  directives: {
    waves
  },
  filters: {
    formatDate,
    getCodeValue(_value, item, remotess) {
      if (remotess && remotess[item.options.remoteFunc]) {
        remotess[item.options.remoteFunc]((data) => {
          item.options.remoteOptions = data.map(items => {
            return {
              value: items[item.options.props.value],
              label: items[item.options.props.label]
            }
          })
        })
        for (const i of item.options.remoteOptions) {
          if (i.value === _value) {
            return i.label
          }
        }
        return _value
      } else {
        for (const i of item.options.options) {
          if (i.value === _value) {
            return i.value
          }
        }
        return _value
      }
    }
  },
  components: {
    GenerateForm
  },
  // eslint-disable-next-line vue/require-prop-types
  props: ['data', 'remote', 'value'],
  data() {
    return {
      sels: [], // 列表选中列
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id',
        tree: true,
        data: {}
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      downloadLoading: false,
      expandAll: false
    }
  },
  computed: {
    // 格式化数据源
    formatData: function() {
      return treeToArray(this.list, this.expandAll)
    }
  },
  created() {
    if (!('table' in this.data)) {
      this.data.table = {}
    }
    this.setValuedefault(this.data.table, 'showRemove', false)
    this.setValuedefault(this.data.table, 'showIndexCol', false)
    this.setValuedefault(this.data.table, 'showEdit', false)
    this.setValuedefault(this.data.table, 'showExport', false)
    this.setValuedefault(this.data.table, 'showAdd', false)
    this.setValuedefault(this.data.table, 'stripe', false)
    this.setValuedefault(this.data.table, 'border', true)
    this.listQuery.data = this.data
    this.getList()
  },
  methods: {
    getList() {
      // debugger
      // this.list = [
      //   /* {
      //     id: 0,
      //     event: '事件1',
      //     timeLine: 50,
      //     comment: '无'
      //   },*/
      //   {
      //     id: 1,
      //     event: '事件1',
      //     timeLine: 100,
      //     comment: '无',
      //     children: [
      //       {
      //         id: 2,
      //         event: '事件2',
      //         timeLine: 10,
      //         comment: '无'
      //       },
      //       {
      //         id: 3,
      //         event: '事件3',
      //         timeLine: 90,
      //         comment: '无',
      //         children: [
      //           {
      //             id: 4,
      //             event: '事件4',
      //             timeLine: 5,
      //             comment: '无'
      //           },
      //           {
      //             id: 5,
      //             event: '事件5',
      //             timeLine: 10,
      //             comment: '无'
      //           },
      //           {
      //             id: 6,
      //             event: '事件6',
      //             timeLine: 75,
      //             comment: '无',
      //             children: [
      //               {
      //                 id: 7,
      //                 event: '事件7',
      //                 timeLine: 50,
      //                 comment: '无',
      //                 children: [
      //                   {
      //                     id: 71,
      //                     event: '事件71',
      //                     timeLine: 25,
      //                     comment: 'xx'
      //                   },
      //                   {
      //                     id: 72,
      //                     event: '事件72',
      //                     timeLine: 5,
      //                     comment: 'xx'
      //                   },
      //                   {
      //                     id: 73,
      //                     event: '事件73',
      //                     timeLine: 20,
      //                     comment: 'xx'
      //                   }
      //                 ]
      //               },
      //               {
      //                 id: 8,
      //                 event: '事件8',
      //                 timeLine: 25,
      //                 comment: '无'
      //               }
      //             ]
      //           }
      //         ]
      //       }
      //     ]
      //   }
      // ]
      // this.listLoading = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    setValuedefault: function(obj, vn, d) {
      if (obj[vn] === false) return
      if (!obj[vn] || obj[vn] === '') {
        obj[vn] = d
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {}
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        (this.$refs.dataForm === undefined ? this.$parent : this).$refs.dataForm.$refs.generateForm.clearValidate()
      })
    },
    createData() {
      (this.$refs.dataForm === undefined ? this.$parent : this).$refs.dataForm.$refs.generateForm.validate((valid) => {
        if (valid) {
          this.temp = Object.assign({}, (this.$refs.dataForm === undefined ? this.$parent : this).$refs.dataForm.$refs.generateForm.model)
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        (this.$refs.dataForm === undefined ? this.$parent : this).$refs.dataForm.$refs.generateForm.clearValidate()
      })
    },
    updateData() {
      (this.$refs.dataForm === undefined ? this.$parent : this).$refs.dataForm.$refs.generateForm.validate((valid) => {
        if (valid) {
          this.temp = Object.assign({}, (this.$refs.dataForm === undefined ? this.$parent : this).$refs.dataForm.$refs.generateForm.model)
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    selsChange: function(sels) {
      this.sels = sels
    },
    batchRemove: function() {
      // var ids = this.sels.map(item => item._id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // this.listLoading = true
        // const para = { ids: ids }
        // this.callBatchRemove(para).then((res) => {
        //   this.listLoading = false
        //   if (res.data.status.code == '0') {
        //     // NProgress.done();
        //     this.$message({
        //       message: '删除成功',
        //       type: 'success'
        //     })
        //   } else {
        //     this.$message({
        //       message: '删除失败:' + res.data.status.msg,
        //       type: 'error'
        //     })
        //   }
        //   this.getRecords()
        // })
        const index = this.list.indexOf(this.sels)
        this.list.splice(index, 1)
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      }).catch(() => {

      })
    },
    showRow: function(row) {
      const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
      row.row._show = show
      return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
    },
    // 切换下级是否展开
    toggleExpanded: function(trIndex) {
      const record = this.formatData[trIndex]
      record._expanded = !record._expanded
    },
    // 图标显示
    iconShow(index, record) {
      return (index === 0 && record.children && record.children.length > 0)
    }

  }
}
</script>
<style rel="stylesheet/css">
  @keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
  @-webkit-keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
</style>

<style lang="scss" rel="stylesheet/scss" scoped>
  $color-blue: #2196F3;
  $space-width: 18px;
  .ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: $space-width;
    height: 14px;
    &::before {
      content: ""
    }
  }
  .processContainer{
    width: 100%;
    height: 100%;
  }
  table td {
    line-height: 26px;
  }

  .tree-ctrl{
    position: relative;
    cursor: pointer;
    color: $color-blue;
    margin-left: -$space-width;
  }
</style>
